package com.harmontronics.hanma.paas.paas.domain.organization.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.harmontronics.hanma.paas.paas.consts.NumberEnum;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.HmOrg;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.HmUser;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.OrgUserExcel;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.OrgUserImportCache;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.OrgUserImportResult;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.valueobject.Constants;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.valueobject.HmOrgFields;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.valueobject.HmUserFields;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.valueobject.HmUserOrgFields;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.valueobject.I18nKeyEnum;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.valueobject.IdentityTypeEnum;
import com.harmontronics.hanma.paas.paas.domain.organization.repository.mapper.HmUserMapper;
import com.harmontronics.hanma.paas.paas.domain.organization.repository.persistence.HmOrgRepository;
import com.harmontronics.hanma.paas.paas.domain.organization.repository.persistence.HmUserOrgRepository;
import com.harmontronics.hanma.paas.paas.domain.organization.repository.persistence.HmUserRepository;
import com.harmontronics.hanma.paas.paas.domain.organization.repository.po.HmOrgPO;
import com.harmontronics.hanma.paas.paas.domain.organization.repository.po.HmUserOrgPO;
import com.harmontronics.hanma.paas.paas.domain.organization.repository.po.HmUserPO;
import com.harmontronics.hanma.paas.paas.exception.ErrorKeyException;
import com.harmontronics.hanma.paas.paas.utils.FileUtil;
import com.harmontronics.hanma.paas.paas.utils.MD5Util;
import com.harmontronics.hanma.paas.paas.utils.PasswordUtil;
import com.harmontronics.hanma.paas.paas.utils.PinYinUtils;
import com.harmontronics.hanma.paas.paas.utils.RequestUtils;
import com.harmontronics.hanma.paas.paas.utils.StringUtil;
import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("hmUserExcelService")
@DS("#header.App-Unique")
public class HmUserImportService {

    @Autowired
    private HmUserRepository hmUserRepository;

    @Autowired
    private HmUserMapper hmUserMapper;

    @Autowired
    private HmOrgService hmOrgService;

    @Autowired
    private HmOrgRepository hmOrgRepository;

    @Autowired
    private HmUserOrgRepository hmUserOrgRepository;

    @Autowired
    private HmUserOrgService hmUserOrgService;


    private String[] importTitle = {"姓名", "性别", "账号", "密码", "部门", "职位", "身份", "负责部门","直属上级","工号","英文名","手机号","座机","邮箱","HID卡号"};


    /**
     * 校验是否是传入正确的excel文件
     *
     * @param reader
     */
    private void checkIsRealImportExcel(ExcelReader reader) {
        // 获取第二行数据
        List<Object> titleObjList = reader.readRow(NumberEnum.ONE.getNum());
        for (int i = NumberEnum.ONE.getNum(); i < titleObjList.size(); i++) {
            String title = StringUtil.getStringFromObj(titleObjList.get(i));
            if (!title.equals(importTitle[i])) {
                throw new ErrorKeyException(I18nKeyEnum.EXCEL_TEMPLATE_NOT_CORRECT);
            }
        }
    }


    public Map<String, Object> importExcelUser(File files, long orgId,Boolean confirm) {
        ExcelReader reader = ExcelUtil.getReader(files);
        checkIsRealImportExcel(reader);
        int count = Math.min(reader.getRowCount(), 1001);
        List<List<Object>> objList = reader.read(2, count);
        reader.close();

        List<OrgUserImportResult> importResultList = new ArrayList<>();
        List<OrgUserImportResult> validateResultList = new ArrayList<>();
        List<String> usernameList = new ArrayList<>();
        List<String> mobileList = new ArrayList<>();
        List<String> jobNumList = new ArrayList<>();
        List<String> hidNoList = new ArrayList<>();
        List<String> emailList = new ArrayList<>();

        if(CollectionUtils.isEmpty(objList)){
            validateResultList.add(new OrgUserImportResult().setRowNum(NumberEnum.ZERO.getNum())
                            .setErrorMsg("导入文件不能为空"));
            importResultList.addAll(validateResultList);

            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("errs", importResultList);
            resultMap.put("oksize", NumberEnum.ZERO.getNum());
            resultMap.put("errsize", NumberEnum.ONE.getNum());

            // 删除文件
            FileUtil.deleteTempFile(files);
            return resultMap;
        }


        List<OrgUserExcel> excelDtoList = new ArrayList<>();
        int serialNum = NumberEnum.TWO.getNum();

        //获取传入部门的完整名称
        String orgFullName = getFullOrgName(orgId);
        //获取根部门的名称
        String[] tmpOrgNames = orgFullName.split("/");
        String orgCascadeName = tmpOrgNames[0];
        for (List<Object> obj : objList) {
            serialNum++;
            String username = "";
            if (obj.size() > NumberEnum.SIX.getNum()) {
                //姓名检验
                String name = StringUtil.getStringFromObj(obj.get(NumberEnum.ZERO.getNum()));
                if (StringUtils.isEmpty(name)) {
                    validateResultList.add(
                            new OrgUserImportResult().setRowNum(serialNum)
                                    .setErrorMsg("姓名不能为空"));
                    continue;
                }
                if (name.length() > 64) {
                    validateResultList.add(
                            new OrgUserImportResult().setRowNum(serialNum).setName(name)
                                    .setErrorMsg("姓名最大长度为64个字符"));
                    continue;
                }


                //性别检验
                String gender = StringUtil.getStringFromObj(obj.get(NumberEnum.ONE.getNum()));
                if (StringUtils.isEmpty(gender)) {
                    validateResultList.add(new OrgUserImportResult().setRowNum(serialNum)
                            .setErrorMsg("性别不能为空"));
                    continue;
                }

                //账号检验
                username = StringUtil.getStringFromObj(obj.get(NumberEnum.TWO.getNum()));
                if (StringUtils.isEmpty(username)) {
                    validateResultList.add(
                            new OrgUserImportResult().setRowNum(serialNum)
                                    .setName(name)
                                    .setErrorMsg("账号不能为空"));
                    continue;
                }

                if(username.contains(":")){
                    String[] names = username.split(":");
                    HmUserPO po = getUserByParam(HmUserFields.USER_NAME,names[1]);
                    if(Optional.ofNullable(po).isPresent()){
                        validateResultList.add(
                                new OrgUserImportResult().setRowNum(serialNum)
                                        .setName(name)
                                        .setErrorMsg("修改的账号名已存在"));
                        continue;
                    }
                    username = names[1];
                }

                if (usernameList.contains(username)) {
                    importResultList.add(
                            new OrgUserImportResult()
                                    .setRowNum(serialNum)
                                    .setName(username)
                                    .setErrorMsg("导入数据中已存在该账号"));
                    continue;
                }
                usernameList.add(username);

                if (username.length() > 32) {
                    validateResultList.add(
                            new OrgUserImportResult().setRowNum(serialNum)
                                    .setName(username)
                                    .setErrorMsg("账号最大长度为32个字符"));
                    continue;
                }

                //该用户是否已离职
                List<HmUserPO> userStatusList =
                        hmUserMapper.selectList(
                                new QueryWrapper<HmUserPO>()
                                        .eq(HmUserFields.USER_NAME, username)
                                        .eq(HmUserFields.DELETED,NumberEnum.ZERO.getNum())
                                        .eq(HmUserFields.STATUS, NumberEnum.TWO.getNum()));
                if(CollectionUtils.isNotEmpty(userStatusList)){
                    validateResultList.add(
                            new OrgUserImportResult().setRowNum(serialNum)
                                    .setName(username)
                                    .setErrorMsg("该用户已离职"));
                    continue;
                }


                //密码检验
                String pwd = StringUtil.getStringFromObj(obj.get(NumberEnum.THREE.getNum()));
                if(StringUtils.isNotBlank(pwd) && !pwd.equals(Constants.D)){
                    if (pwd.length() > 32 || pwd.length() <6) {
                        validateResultList.add(
                                new OrgUserImportResult().setRowNum(serialNum)
                                        .setName(name)
                                        .setErrorMsg("密码长度为6-32位数字"));
                        continue;
                    }
                }

                // 组织部门检验
                String orgNames = StringUtil.getStringFromObj(obj.get(NumberEnum.FOUR.getNum()));
                if(StringUtils.isNotBlank(orgNames) && !orgNames.equals(Constants.E)){
                    boolean orgError = false;
                    for (String orgName : orgNames.split(";")) {
                        String[] orgSegments = orgName.split("/");
                        if (!orgSegments[0].equals(orgCascadeName)) {
                            validateResultList.add(new OrgUserImportResult().setRowNum(serialNum).setName(name)
                                    .setErrorMsg(RequestUtils.localeMessage(I18nKeyEnum.ORG_IMPORT_NAME_PREFIX_ERROR.getI18nKey())));
                            orgError = true;
                            break;
                        }
                        for (String orgSegName : orgSegments) {
                            if (orgSegName.length() > 32) {
                                validateResultList.add(new OrgUserImportResult().setRowNum(serialNum).setName(name)
                                        .setErrorMsg(RequestUtils.localeMessage(I18nKeyEnum.ORG_IMPORT_NAME_TOO_LONG.getI18nKey())));
                                orgError = true;
                                break;
                            }
                        }
                    }
                    if (orgError) {
                        continue;
                    }
                }else{
                    orgNames = orgFullName;
                }


                //身份检验
                String identityType = StringUtil.getStringFromObj(obj.get(NumberEnum.SIX.getNum()));
                if (StringUtils.isEmpty(identityType)) {
                    validateResultList.add(new OrgUserImportResult().setRowNum(serialNum)
                            .setName(name)
                            .setErrorMsg("身份不能为空"));
                    continue;
                }

                // 负责部门检验
                if(obj.size() > NumberEnum.EIGHT.getNum()){
                    String manageOrg = StringUtil.getStringFromObj(obj.get(NumberEnum.SEVEN.getNum()));
                    if(identityType.equals(IdentityTypeEnum.HIGHER.getDescription())){
                        if (StringUtils.isEmpty(manageOrg)) {
                            validateResultList.add(new OrgUserImportResult().setRowNum(serialNum)
                                    .setName(name)
                                    .setErrorMsg("负责部门不能为空"));
                            continue;
                        }
                        List<String> manageOrgList = Arrays.asList( manageOrg.split(";"));
                        List<String> orgNameList = Arrays.asList(orgNames.split(";"));
                        if(manageOrgList.size() > orgNameList.size()){
                            validateResultList.add(new OrgUserImportResult().setRowNum(serialNum)
                                    .setName(name)
                                    .setErrorMsg("负责部门必须在所属范围内"));
                            continue;
                        }else{
                            Boolean contains = true;
                            for (String manageOrgName : manageOrgList) {
                                if(!orgNameList.contains(manageOrgName)){
                                    contains = false;
                                }
                            }
                            if(!contains){
                                validateResultList.add(new OrgUserImportResult().setRowNum(serialNum)
                                        .setName(name)
                                        .setErrorMsg("负责部门必须在所属范围内"));
                                continue;
                            }
                        }
                        Boolean nameLong = true;
                        for(String tmpManageOrg : manageOrgList){
                            String[] manageOrgSegNames = tmpManageOrg.split("/");
                            for(String manageOrgSegName : manageOrgSegNames){
                                if(manageOrgSegName.length() > 32){
                                    nameLong = false;
                                }
                            }
                        }
                        if(!nameLong){
                            validateResultList.add(new OrgUserImportResult().setRowNum(serialNum)
                                    .setName(name)
                                    .setErrorMsg("负责部门长度不超过32字符"));
                            continue;
                        }
                    }
                }

                if(obj.size() > NumberEnum.NINE.getNum()){
                    //工号检验
                    String jobNum = StringUtil.getStringFromObj(obj.get(NumberEnum.NINE.getNum()));
                    if(StringUtils.isNotBlank(jobNum) && !jobNum.equals(Constants.J)){
                        if (jobNum.length() > 32) {
                            validateResultList.add(
                                    new OrgUserImportResult().setRowNum(serialNum)
                                            .setName(name)
                                            .setErrorMsg("工号最大长度为32个字符"));
                            continue;
                        } else {
                            if (jobNumList.contains(jobNum)) {
                                importResultList.add(
                                        new OrgUserImportResult()
                                                .setRowNum(serialNum)
                                                .setName(name)
                                                .setErrorMsg("导入数据中已存在该工号"));
                                continue;
                            }
                            jobNumList.add(jobNum);
                            // 判断工号存不存在 或者 人员是否离职
                            HmUserPO user =
                                    hmUserMapper.selectOne(
                                            new QueryWrapper<HmUserPO>().eq(HmUserFields.JOB_NUMBER, jobNum)
                                                    .eq(HmUserFields.DELETED, NumberEnum.ZERO.getNum())
                                                    .ne(HmUserFields.USER_NAME,username));
                            if (user != null) {
                                importResultList.add(
                                        new OrgUserImportResult()
                                                .setRowNum(serialNum)
                                                .setName(name)
                                                .setErrorMsg("该员工已存在"));
                                continue;
                            }
                        }
                    }
                }

                if(obj.size() > 11){
                    //手机号码检测
                    String mobile = StringUtil.getStringFromObj(obj.get(11));
                    if(StringUtils.isNotBlank(mobile) && !mobile.equals(Constants.L)){
                        if (mobile.trim().length() != 11) {
                            importResultList.add(
                                    new OrgUserImportResult()
                                            .setRowNum(serialNum)
                                            .setName(name)
                                            .setErrorMsg("手机号码不合法"));
                            continue;
                        } else {
                            // 判断当前上传文件中是否有重复的手机号
                            if (mobileList.contains(mobile)) {
                                importResultList.add(
                                        new OrgUserImportResult()
                                                .setRowNum(serialNum)
                                                .setName(name)
                                                .setErrorMsg("导入数据中已存在该手机号"));
                                continue;
                            }
                            mobileList.add(mobile);

                            // 根据手机号，判断是否存在，去除当前人员
                            List<HmUserPO> userList =
                                    hmUserMapper.selectList(
                                            new QueryWrapper<HmUserPO>()
                                                    .eq(HmUserFields.MOBILE, mobile.trim())
                                                    .ne(HmUserFields.USER_NAME, username)
                                                    .eq(HmUserFields.DELETED, NumberEnum.ZERO.getNum()));
                            if (CollectionUtils.isNotEmpty(userList)) {
                                importResultList.add(
                                        new OrgUserImportResult()
                                                .setRowNum(serialNum)
                                                .setName(name)
                                                .setErrorMsg("手机号已存在"));
                                continue;
                            }
                        }
                    }
                }



                if(obj.size() > 13){
                    //邮箱检验
                    String email = StringUtil.getStringFromObj(obj.get(13));
                    if (StringUtils.isNotBlank(email) && !email.equals(Constants.N)) {
                        if (email.length() > 128) {
                            importResultList.add(
                                    new OrgUserImportResult()
                                            .setRowNum(serialNum)
                                            .setName(name)
                                            .setErrorMsg("邮箱最大长度为128字符"));
                            continue;
                        }
                        if (emailList.contains(email)) {
                            importResultList.add(
                                    new OrgUserImportResult()
                                            .setRowNum(serialNum)
                                            .setName(name)
                                            .setErrorMsg("导入数据中已存在该邮箱"));
                            continue;
                        }
                        List<HmUserPO> userList =
                                hmUserMapper.selectList(
                                        new QueryWrapper<HmUserPO>()
                                                .eq(HmUserFields.EMAIL, email)
                                                .ne(HmUserFields.USER_NAME, username)
                                                .eq(HmUserFields.DELETED,
                                                        NumberEnum.ZERO.getNum()));
                        if (CollectionUtils.isNotEmpty(userList)) {
                            importResultList.add(
                                    new OrgUserImportResult()
                                            .setRowNum(serialNum)
                                            .setName(name)
                                            .setErrorMsg("该邮箱已存在"));
                            continue;
                        }
                        emailList.add(email);
                    }
                }


                if(obj.size() > 14){
                    String hidNo = StringUtil.getStringFromObj(obj.get(14));
                    if (StringUtils.isNotBlank(hidNo) && !hidNo.equals(Constants.O)) {
                        if (hidNoList.contains(hidNo)) {
                            importResultList.add(
                                    new OrgUserImportResult()
                                            .setRowNum(serialNum)
                                            .setName(name)
                                            .setErrorMsg("导入数据中已存在该HID卡号"));
                            continue;
                        }
                        hidNoList.add(hidNo);
                        // 判断hid卡号是否存在，去除当前人员
                        List<HmUserPO> userList =
                                hmUserMapper.selectList(
                                        new QueryWrapper<HmUserPO>()
                                                .eq(HmUserFields.HID_NO, hidNo)
                                                .ne(HmUserFields.USER_NAME, username)
                                                .eq(HmUserFields.STATUS, NumberEnum.ONE.getNum())
                                                .eq(HmUserFields.DELETED,
                                                        NumberEnum.ZERO.getNum()));
                        if (CollectionUtils.isNotEmpty(userList)) {
                            importResultList.add(
                                    new OrgUserImportResult()
                                            .setRowNum(serialNum)
                                            .setName(name)
                                            .setErrorMsg("HID卡号已存在"));
                            continue;
                        }
                    }
                }
            }
            OrgUserExcel excelDto = getExcelDtoFromObj(obj);
            excelDtoList.add(excelDto);
        }

        importResultList.addAll(validateResultList);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("errs", importResultList);
        resultMap.put("oksize", excelDtoList.size());
        resultMap.put("errsize", importResultList.size());

        // 删除文件
        FileUtil.deleteTempFile(files);

        if(confirm){
            try{
                insertExcelData(excelDtoList,orgId);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return resultMap;
    }

    /**
     * 组装数据
     *
     * @param objList
     * @return
     */
    private OrgUserExcel getExcelDtoFromObj(List<Object> objList) {
        return new OrgUserExcel()
                .setName(StringUtil.getStringFromObj(objList.get(0)))
                .setGender(StringUtil.getStringFromObj(objList.get(1)))
                .setUsername(StringUtil.getStringFromObj(objList.get(2)))
                .setPassword(StringUtil.getStringFromObj(objList.get(3)))
                .setOrgName(StringUtil.getStringFromObj(objList.get(4)))
                .setPosition(StringUtil.getStringFromObj(objList.get(5)))
                .setIdentityType(StringUtil.getStringFromObj(objList.get(6)))
                .setManageOrg(objList.size() > 7 ? StringUtil.getStringFromObj(objList.get(7)) : null)
                .setHigherName(objList.size() > 8 ? StringUtil.getStringFromObj(objList.get(8)) : null)
                .setJobNumber(objList.size() > 9 ? StringUtil.getStringFromObj(objList.get(9)) : null)
                .setEnglishName(objList.size() > 10 ? StringUtil.getStringFromObj(objList.get(10)) : null)
                .setMobile(objList.size() > 11 ? StringUtil.getStringFromObj(objList.get(11)) : null)
                .setTelephone(objList.size() > 12 ? StringUtil.getStringFromObj( objList.get(12)) : null)
                .setEmail(objList.size() > 13 ? StringUtil.getStringFromObj( objList.get(13)) : null)
                .setHidNo(objList.size() > 14 ? StringUtil.getStringFromObj( objList.get(14)) : null);
    }

    /**
     * 只能一个一个的插，没办法批量 因为涉及到用户-组织架构 关联关系表
     *
     * @param excelDtoList
     * @param orgId
     */
    private void insertExcelData(List<OrgUserExcel> excelDtoList, Long orgId) throws InterruptedException{
        HmOrg rootOrg = hmOrgService.getRootOrg();
        String rootOrgName = rootOrg.getName();
        Map<String, Long> orgNameTreeMap =
        hmOrgService.selectOrgTreeWithOrgId(rootOrg.getId());
        for (OrgUserExcel excelDto : excelDtoList) {
            // 获取当前用户对应的所有组织节点id
            List<Long> orgIds = new ArrayList<>();
            String orgName = excelDto.getOrgName();
            if(StringUtils.isNotBlank(excelDto.getOrgName()) && !rootOrgName.equals(orgName)){
                String subOrgName = orgName.substring(orgName.indexOf("/")+1);
                orgIds = dealOrgName(subOrgName, orgNameTreeMap, orgId);
                Thread.sleep(10);
            }else{
                orgIds.add(orgId);
            }


            if(excelDto.getIdentityType().equals(IdentityTypeEnum.HIGHER.getDescription())){
                List<Long> manageOrgs = new ArrayList<>();
                String manageOrgName = excelDto.getManageOrg();
                if(StringUtils.isNotBlank(manageOrgName)){
                    if(!manageOrgName.equals(rootOrgName)){
                        String subManageOrgName = manageOrgName.substring(manageOrgName.indexOf("/")+1);
                        manageOrgs = dealOrgName(subManageOrgName,orgNameTreeMap,orgId);
                        if(CollectionUtils.isNotEmpty(manageOrgs)){
                            String manageOrgStr = "";
                            for (Long manageOrgId : manageOrgs) {
                                manageOrgStr =  Constants.LEFT_SQUARE_BRACKETS
                                        +manageOrgId+Constants
                                        .RIGHT_SQUARE_BRACKETS
                                        + manageOrgStr;
                            }
                            excelDto.setManageOrg(manageOrgStr);
                        }
                    }else{
                         String manageOrgStr =  Constants.LEFT_SQUARE_BRACKETS
                                +rootOrg.getId()+Constants
                                .RIGHT_SQUARE_BRACKETS;
                        excelDto.setManageOrg(manageOrgStr);
                    }

                }
            }

            // 结合组织节点id，写入数据库
            dealExcelUser(excelDto,orgIds);
        }
    }


    private void dealExcelUser(OrgUserExcel excelDto, List<Long> orgIds)
            throws ErrorKeyException {
        HmUser createDto = dealUserBasicInfo(excelDto,orgIds);
        createDto.setOrgIds(orgIds);
        insertIntoDb(createDto);
    }


    private void insertIntoDb(HmUser user) {
        // 插入user表
        HmUserPO insertUser = BeanUtil.toBean(user, HmUserPO.class);
        // 密码 salt设置

        if(StringUtils.isNotBlank(user.getNewPassword())){
            Map<String, String> pwdMap = PasswordUtil.generatePassword(MD5Util.MD5(user.getNewPassword()));
            insertUser.setPassword(pwdMap.get(HmUserFields.PWD));
            insertUser.setSalt(pwdMap.get(HmUserFields.SALT));
        }

        insertUser.setFullPinyin(PinYinUtils.getHanziPinYin(user.getName(), Boolean.TRUE));
        insertUser.setSimplicity(PinYinUtils.getHanziInitials(user.getName(), Boolean.TRUE));
        insertUser.setDeleted(NumberEnum.ZERO.getNum());
        insertUser.setStatus(NumberEnum.ONE.getNum());
        insertUser.setIsSuperAdmin(false);
        insertUser.setPhoneRegion(HmUserFields.DEFAULT_PHONE_REGION);
        insertUser.setModifyDate(LocalDateTime.now());
        insertUser.setCreateDate(LocalDateTime.now());
        hmUserRepository.saveOrUpdate(insertUser);

        // 插入user_org表
        insertUserOrgs(user.getOrgIds(), insertUser.getId());
    }

    private void insertUserOrgs(List<Long> orgIds, Long userId) {
        //删除之前的关系
        List<HmUserOrgPO> existUserOrgList =
                hmUserOrgRepository.list(
                        new QueryWrapper<HmUserOrgPO>()
                                .eq(HmUserOrgFields.USER_ID, userId)
                                .eq(HmUserOrgFields.DELETED, NumberEnum.ZERO.getNum()));
        if(CollectionUtils.isNotEmpty(existUserOrgList)){
            List<Integer> idList = existUserOrgList.stream().map(HmUserOrgPO::getId).collect(Collectors.toList());
            hmUserOrgRepository.removeByIds(idList);
        }

        // 插入user_org表
        List<HmUserOrgPO> userOrgList = new ArrayList<>();
        for (Long orgId : orgIds) {
            HmUserOrgPO userOrg = new HmUserOrgPO();
            userOrg.setUserId(userId);
            userOrg.setOrgId(orgId);
            userOrg.setDeleted(NumberEnum.ZERO.getNum());
            userOrgList.add(userOrg);
        }
        hmUserOrgRepository.saveBatch(userOrgList);
    }

    private HmUser dealUserBasicInfo(OrgUserExcel excelDto,List<Long> orgIdList){
        HmUser createUser = new HmUser();
        String username = excelDto.getUsername();
        //更新账号，先根据老账号查询
        if(username.contains(":")){
            String[] usernames = username.split(":");
            String oldName = usernames[0];
            String newName = usernames[1];
            HmUserPO userPo = getUserByParam(HmUserFields.USER_NAME,oldName);
            userPo.setUsername(newName);
            createUser = BeanUtil.toBean(userPo,HmUser.class);
        }else{
            //先根据账号查询用户是否存在，如果存在则是更新操作
            HmUserPO userPo = getUserByParam(HmUserFields.USER_NAME,username);
            if(Optional.ofNullable(userPo).isPresent()){
                createUser = BeanUtil.toBean(userPo,HmUser.class);
            }else{
                createUser.setUsername(username);
            }
        }

        //第一个部门设置成主部门
        if(CollectionUtils.isNotEmpty(orgIdList)){
            createUser.setOrgId(orgIdList.get(0));
        }

        createUser.setName(excelDto.getName());
        createUser.setGender(Constants.FEMALE.equals(excelDto.getGender()) ? 0 : 1);
        String position = excelDto.getPosition();
        if(StringUtils.isNotBlank(position) && !position.equals(Constants.F)){
            createUser.setPosition(position);
        }


        String identityType = excelDto.getIdentityType();
        if(identityType.equals(IdentityTypeEnum.NORMAL.getDescription())){
            createUser.setIdentityType(IdentityTypeEnum.NORMAL);
        }else{
            createUser.setIdentityType(IdentityTypeEnum.HIGHER);
        }


        String password = excelDto.getPassword();
        //密码不为空则设置新密码
        if(StringUtils.isNotBlank(password) && !password.equals(Constants.D)){
            createUser.setNewPassword(password.trim());
        }else{
            //如果密码为空，且新增时使用默认初始化密码
            if(createUser.getId() == null){
                createUser.setNewPassword(Constants.INIT_PASSWORD);
            }
        }

        //如果身份是上级，则设置负责部门
        if(createUser.getIdentityType().equals(IdentityTypeEnum.HIGHER)){
            if(StringUtils.isNotBlank(excelDto.getManageOrg())){
                createUser.setManageOrg(excelDto.getManageOrg());
            }
        }


        String higherName = excelDto.getHigherName();
        if(StringUtils.isNotBlank(higherName) && !higherName.equals(Constants.I)){
            HmUserPO higher = new HmUserPO();
            //如果所属上级包含账号，则根据账号去查询，否则根据用户名查询
            if(higherName.contains(":")){
                String[] higherNames = higherName.split(":");
                higher = getUserByParam(HmUserFields.USER_NAME,higherNames[0]);
            }else{
                higher = getUserByParam(HmUserFields.NAME,higherName);
            }
            if(Optional.ofNullable(higher).isPresent()){
                createUser.setHigherId(higher.getId());
            }
        }

        String jobNumber = excelDto.getJobNumber();
        if(StringUtils.isNotBlank(jobNumber) && !jobNumber.equals(Constants.J)){
            createUser.setJobNumber(jobNumber);
        }

        String mobile = excelDto.getMobile();
        if(StringUtils.isNotBlank(mobile) && !mobile.equals(Constants.L)){
            createUser.setMobile(mobile);
        }

        String email = excelDto.getEmail();
        if(StringUtils.isNotBlank(email) && !email.equals(Constants.N)){
            createUser.setEmail(email);
        }

        String hidNo = excelDto.getHidNo();
        if(StringUtils.isNotBlank(hidNo) && !hidNo.equals(Constants.O)){
            createUser.setHidNo(hidNo);
        }

        return createUser;
    }


    /**
     * 处理excel中传入的部门，判断数据库中是否存在
     *
     * @param orgName
     * @param orgNameTreeMap
     * @param parentId
     * @return
     */
    private List<Long> dealOrgName(String orgName, Map<String, Long> orgNameTreeMap,
            Long parentId) {
        List<String> orgNameList = new ArrayList<>();
        if (orgName.contains(";")) {
            String[] nameArr = orgName.split(";");
            orgNameList.addAll(Arrays.asList(nameArr));
        } else {
            orgNameList.add(orgName);
        }
        List<Long> orgIds = new ArrayList<>();
        for (String name : orgNameList) {
            //兼容 尾部有 /的情况
            if (name.endsWith("/")) {
                name = name.substring(0, name.length() - 1);
            }
            Long orgId = orgNameTreeMap.get(name);
            if (orgId != null) {
                orgIds.add(orgId);
            } else {
                // 说明组织架构中没有找到合适的，需要新建
                orgId = dealOrgWithExcelOrgName(name, parentId);
                orgIds.add(orgId);
            }
        }
        return orgIds;
    }

    /**
     * 新增组织架构
     *
     * @param name
     * @param parentId
     * @return
     */
    private Long dealOrgWithExcelOrgName(String name, Long parentId) {
        String[] nameArr = name.split("/");
        Long orgId = parentId;
        String parentIds = null;
        if (nameArr.length >= 1) {
            for (int i = 0; i < nameArr.length; i++) {
                String orgName = nameArr[i];
                QueryWrapper orgQuery =
                        new QueryWrapper<HmOrgPO>()
                                .eq(HmOrgFields.NAME, orgName)
                                .eq(HmOrgFields.DELETED, NumberEnum.ZERO.getNum());
                if (orgId != null) {
                    orgQuery.eq(HmOrgFields.PARENT_ID, orgId);
                }
                HmOrgPO org = hmOrgRepository.getOne(orgQuery);
                // 返回组织架构节点ID，继续下一步
                if (org == null) {
                    // 没有找到，新建一个，并返回新建的id
                    HmOrgPO parentOrg = hmOrgRepository.getById(orgId);
                    String pIds = parentOrg.getParentIds() == null ? "" : parentOrg.getParentIds();
                    parentIds =
                            pIds
                                    + Constants.LEFT_SQUARE_BRACKETS
                                    + orgId
                                    + Constants.RIGHT_SQUARE_BRACKETS;
                    Long count = hmOrgService.selectMaxSerialNum(orgId) + NumberEnum.ONE.getNum();
                    org = new HmOrgPO();
                    org.setName(orgName);
                    org.setSerialNum(count);
                    org.setParentId(orgId);
                    org.setParentIds(parentIds);
                    org.setDeleted(NumberEnum.ZERO.getNum());
                    hmOrgRepository.save(org);
                }

                orgId = org.getId();
                parentIds =
                        org.getParentIds()
                                + Constants.LEFT_SQUARE_BRACKETS
                                + orgId
                                + Constants.RIGHT_SQUARE_BRACKETS;
            }
        }
        return orgId;
    }

    private HmUserPO getUserByParam(String key,String value){
        List<HmUserPO> userList = hmUserRepository.list(new QueryWrapper<HmUserPO>()
                .eq(key,value)
                .eq(HmUserFields.STATUS, NumberEnum.ONE.getNum())
                .eq(HmUserFields.DELETED,NumberEnum.ZERO.getNum()));
        if(CollectionUtils.isNotEmpty(userList)){
            return userList.get(0);
        }else{
            return null;
        }
    }


    private String getFullOrgName(Long orgId){
        HmOrgPO org = hmOrgRepository.getById(orgId);
        String parentIds = org.getParentIds();
        if(StringUtils.isNotBlank(parentIds)){
            String[] tmpParentIds = parentIds.replace(Constants.LEFT_SQUARE_BRACKETS,"")
                    .split(Constants.RIGHT_SQUARE_BRACKETS);
            List<Long> parentIdList = Arrays.stream(tmpParentIds).map(id -> Long.parseLong(id))
                    .collect(Collectors.toList());
            List<HmOrgPO> parentOrgList = hmOrgRepository.listByIds(parentIdList);
            parentOrgList = parentOrgList.stream().sorted(Comparator.comparing(HmOrgPO::getId) ).collect(Collectors.toList());
            String fullOrgName = "";
            for (HmOrgPO tmpOrg : parentOrgList) {
                fullOrgName = fullOrgName + "/" + tmpOrg.getName();
            }
            fullOrgName = fullOrgName + "/" + org.getName();
            return fullOrgName.substring(1);
        }else{
            return org.getName();
        }
    }

}
